package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.mapper.AddressBookMapper;
import com.itheima.reggie.service.AddressBookService;
import org.springframework.stereotype.Service;

@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements AddressBookService {

    @Override
    public void del(Long ids) {
        //判断该地址是否为默认收获地址
        Integer isDefault = this.getById(ids).getIsDefault();
        if (isDefault == 0) {
            //不是就直接删除
            this.removeById(ids);
        }
        if (isDefault == 1) {
            //若是先删除该地址，再将最新更新的地址设置为默认地址
            this.removeById(ids);
            AddressBook address = this.getOne(Wrappers.<AddressBook>lambdaQuery()
                    .eq(AddressBook::getUserId, BaseContext.getCurrentId())
                    .orderByDesc(AddressBook::getUpdateTime)
                    .last("limit 0,1"));
            address.setIsDefault(1);
            this.updateById(address);
        }
    }

}
